package com.lazypeople.task.impl;

import javafx.application.Platform;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

import com.lazypeople.domain.DownloadStatus;
import com.lazypeople.domain.DownloadTask;
import com.lazypeople.domain.ProgressListener;
import com.lazypeople.task.DownloadThread;
import com.lazypeople.util.FileUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpDownloadTask extends DownloadTask {
    private static final Logger logger = LoggerFactory.getLogger(HttpDownloadTask.class);
    private final AtomicLong downloadedBytes = new AtomicLong(0);
    private long totalBytes = -1;
    private DownloadStatus status = DownloadStatus.READY;
    private final List<DownloadThread> threads = new ArrayList<>();
    private final List<ProgressListener> listeners = new ArrayList<>();
    private ExecutorService threadPool;
    private File tempFile;

    public HttpDownloadTask(String url, File saveFile, int threadCount) {
        super(url, saveFile, threadCount);
    }

    @Override
    public void run() {
        this.tempFile = new File(this.getSaveFile().getAbsolutePath() + ".temp");
        status = DownloadStatus.DOWNLOADING;
        appendLog("开始HTTP下载任务: " + this.getUrl() + "\n");

        try {
            // 检查是否有断点续传信息
            long[] ranges = new long[this.getThreadCount()];
            long[] downloaded = new long[this.getThreadCount()];
            long existingDownloaded = 0;
            URL httpUrl = new URL(this.getUrl());

            if (tempFile.exists()) {
                try (BufferedReader reader = new BufferedReader(new FileReader(tempFile))) {
                    // totalBytes = Long.parseLong(reader.readLine());
                    for (int i = 0; i < this.getThreadCount(); i++) {
                        String line = reader.readLine();
                        if (line != null) {
                            String[] parts = line.split(",");
                            ranges[i] = Long.parseLong(parts[0]);
                            downloaded[i] = Long.parseLong(parts[1]);
                            existingDownloaded += downloaded[i];
                        }
                    }
                }
                downloadedBytes.set(existingDownloaded);
                appendLog("检测到断点续传信息，已下载: " + FileUtils.formatFileSize(existingDownloaded) + "\n");
            } else {
                // 获取文件总大小
                HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
                totalBytes = connection.getContentLengthLong();
                connection.disconnect();

                if (totalBytes <= 0) {
                    appendLog("无法获取文件大小，可能不支持断点续传\n");
                    totalBytes = -1;
                } else {
                    appendLog("文件总大小: " + FileUtils.formatFileSize(totalBytes) + "\n");
                    // 计算每个线程负责的范围
                    long blockSize = totalBytes / this.getThreadCount();
                    for (int i = 0; i < this.getThreadCount(); i++) {
                        ranges[i] = (i == this.getThreadCount() - 1) ? totalBytes - 1 : (i + 1) * blockSize - 1;
                        downloaded[i] = 0;
                    }
                }
            }

            // 更新进度条
            notifyProgressChanged();

            // 创建线程池
            threadPool = Executors.newFixedThreadPool(this.getThreadCount());

            // 创建并启动下载线程
            long startPos = 0;
            for (int i = 0; i < this.getThreadCount(); i++) {
                appendLog("线程序号: " + i + "\n");
                DownloadThread thread = new DownloadThread(httpUrl, this.getSaveFile(), startPos + downloaded[i],
                        ranges[i],
                        downloadedBytes, i, downloaded, tempFile);
                threads.add(thread);
                threadPool.execute(thread);
                startPos = ranges[i] + 1;
            }

            // 等待所有线程完成
            threadPool.shutdown();
            while (!threadPool.isTerminated()) {
                Thread.sleep(1000);
                notifyProgressChanged();

                if (status == DownloadStatus.PAUSED || status == DownloadStatus.CANCELLED) {
                    break;
                }
            }

            // 检查下载状态
            if (status == DownloadStatus.DOWNLOADING && getProgress() == 100) {
                status = DownloadStatus.COMPLETED;
                if (tempFile.exists()) {
                    tempFile.delete();
                }
                appendLog("下载完成: " + getSaveFile().getName());
            } else if (status == DownloadStatus.PAUSED) {
                appendLog("下载已暂停: " + getSaveFile().getName());
            } else if (status == DownloadStatus.CANCELLED) {
                if (this.getSaveFile().exists()) {
                    this.getSaveFile().delete();
                }
                if (tempFile.exists()) {
                    tempFile.delete();
                }
                appendLog("下载已取消: " + getSaveFile().getName());
            }
        } catch (Exception e) {
            status = DownloadStatus.FAILED;
            appendLog("下载失败: " + e.getMessage() + "\n");
            e.printStackTrace();
        } finally {
            notifyProgressChanged();
        }
    }

    @Override
    public void pause() {
        if (status == DownloadStatus.DOWNLOADING) {
            status = DownloadStatus.PAUSED;
            if (threadPool != null) {
                threadPool.shutdownNow();
            }
            for (DownloadThread thread : threads) {
                thread.pause();
            }
            appendLog("暂停下载: " + getSaveFile().getName());
        }
    }

    @Override
    public void resume() {
        if (status == DownloadStatus.PAUSED) {
            status = DownloadStatus.DOWNLOADING;

            new Thread(this).start();
            appendLog("恢复下载: " + getSaveFile().getName());
        }
    }

    @Override
    public void cancel() {
        if (status == DownloadStatus.DOWNLOADING || status == DownloadStatus.PAUSED) {
            status = DownloadStatus.CANCELLED;
            if (threadPool != null) {
                threadPool.shutdownNow();
            }
            for (DownloadThread thread : threads) {
                thread.cancel();
            }
            appendLog("取消下载: " + getSaveFile().getName());
        }
    }

    @Override
    public DownloadStatus getStatus() {
        return status;
    }

    @Override
    public long getDownloadedBytes() {
        return downloadedBytes.get();
    }

    @Override
    public long getTotalBytes() {
        return totalBytes;
    }

    @Override
    public float getProgress() {
        if (totalBytes <= 0) {
            return 0;
        }
        return (float) (downloadedBytes.get() * 100.00 / totalBytes);
    }

    // 添加缺失的接口方法实现
    @Override
    public void addProgressListener(ProgressListener listener) {
        // 实现进度监听器添加逻辑
        appendLog("HttpDowloadTask:addProgressListener 添加监听");
        listeners.add(listener);
    }

    @Override
    public void removeProgressListener(ProgressListener listener) {
        // 实现进度监听器移除逻辑
        appendLog("HttpDowloadTask:listener移除");
        listeners.remove(listener);
    }

    private void notifyProgressChanged() {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                for (ProgressListener listener : listeners) {
                    listener.onProgressChanged(getProgress(), getDownloadedBytes(), getTotalBytes());
                }
            }
        });
    }

    // 添加日志追加的封装方法，确保UI线程安全
    private void appendLog(String text) {
        Platform.runLater(() -> logger.info(text));
    }
}
